package com.caiheng.api.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.estate.*;
import com.caiheng.api.service.platfom.SmsTemplateService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  报修记录
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/customer/sms/record")//url:模块/资源/{}/细分
public class CustomerSmsRecordController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private EstateRoomService estateRoomService;
    @Resource
    private EstateService estateService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private EstateCustomerSmsRecordService estateCustomerSmsRecordService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private SmsTemplateService smsTemplateService;
    @Resource
    private LockTemplate lockTemplate;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片地址

    /**
     * 上报
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add")
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();

        logBefore(logger, "customer/call/record/add 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        String startDate = jsonRequest.containsKey("startDate") ? jsonRequest.getStr("startDate") : "";

        final LockInfo lockInfo = lockTemplate.lock(user_id + "_addCallRecord_" + user_id, 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            int room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateUser estateUser = estateUserService.getEstateUser(user_id);
            if(estateUser!= null){
            }

            String estateName = "";
            EstateRoom room = estateRoomService.findById(room_id);
            if(room == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该住户不存在"),true,true);
            }

            Estate estate = estateService.findById(room.getEstateId());
            if(estate!= null){
                estateName = estate.getEstateName();
            }

            List<String> phoneList = PhoneUtils.getPhoneListByStr(room.getPhoneNum());
            if(CollUtil.isEmpty(phoneList)){
                for (String phone : phoneList){

                    EstateCustomerSmsRecord smsRecord = new EstateCustomerSmsRecord();
                    smsRecord.setEstateId(room.getEstateId());
                    smsRecord.setEstateName(estateName);

                    smsRecord.setPhoneNum(room.getPhoneNum());
                    smsRecord.setRoomNo(room.getRoomNo());
                    smsRecord.setRoomRealName(room.getRealName());

                    smsRecord.setRoomId(room_id);
                    smsRecord.setWxUserId(user_id);
                    smsRecord.setSendTime(new Date());
                    smsRecord.setRemark(remark);
                    smsRecord.setSmsState(0);

                    //String year, String month1, String month2, BigDecimal money, String telephone
//                    smsTemplateService.sendSmsByPropertyFeeToRooUser(phone, room,
//                            feeOrderTemplate1.getYearNum(), feeOrderTemplate1.getMonthNum(), feeOrderTemplate2.getMonthNum(), new BigDecimal(money), telephone);
                    estateCustomerSmsRecordService.save(smsRecord);
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"发送成功"),true,true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     * 我的上报列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject recordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "customer/call/record/list 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : -1;
            int room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateRoom room = estateRoomService.findById(room_id);
            if(room == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该房间不存在"),true,true);
            }

            QueryWrapper<EstateCustomerSmsRecord> qw = new QueryWrapper<>();
            qw.eq("wx_user_id", user_id);
            if(state > -1){
                qw.eq("state", state);
            }
            qw.eq("room_id", room_id);
            qw.orderByDesc("send_time");
            List<EstateCustomerSmsRecord> list = estateCustomerSmsRecordService.getPageEntityList(qw, pageIndex,pageSize);
            map.put("recordList", list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(), map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }
}
